import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "@/lib/utils";

const buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium facet-hover-fade focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default:
          "bg-facet-blue text-white shadow",
        destructive:
          "bg-destructive text-destructive-foreground shadow-sm",
        outline:
          "border border-input bg-background shadow-sm",
        secondary:
          "bg-secondary text-secondary-foreground shadow-sm",
        ghost: "",
        link: "text-primary underline-offset-4 hover:underline",
        facet: "bg-facet-gradient text-white shadow-lg",
        wine: "bg-facet-wine text-white shadow",
        teal: "bg-facet-teal text-white shadow",
        therapy: "bg-therapy-calm text-white shadow",
        crisis: "bg-red-600 text-white shadow-lg animate-pulse border-2 border-red-300",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-12 rounded-md px-8 text-base",
        xl: "h-14 rounded-lg px-10 text-lg font-semibold",
        icon: "h-9 w-9",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
);

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean;
  loading?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, loading = false, ...props }, ref) => {
    // 当loading为true时，禁用按钮
    const buttonProps = { ...props, disabled: props.disabled || loading };

    // 如果需要显示加载状态，可以在这里添加逻辑
    const Comp = asChild ? Slot : "button";
    return (
        <Comp
          className={cn(buttonVariants({ variant, size, className }))}
          ref={ref}
          {...buttonProps}
        />
      );
  }
);
Button.displayName = "Button";

export { Button, buttonVariants };